package com.succez.server.servlet.http;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.succez.server.servlet.Consts;
import com.succez.server.servlet.Request;
import com.succez.server.servlet.Response;
import com.succez.server.servlet.Servlet;
import com.succez.server.utils.CloseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认的静态资源处理servlet，直接从静态目录读取并返回html、css、js、img
 */
public class StaticResourceServlet extends Servlet {
    /**
     * 日志记录
     */
    private static final Logger logger = LoggerFactory.getLogger(StaticResourceServlet.class);

    @Override
    protected void doPost(Response response, Request request) {
        // do nothing

    }

    @Override
    protected void doGet(Response response, Request request) {
        File directory = new File(".");
        File file = null;
        try {
            file = new File(directory.getCanonicalPath() + Consts.STATIC_DIR + request.getUrl().replace("/", "\\"));
        } catch (IOException e) {
            logger.error("获取指定的文件时出错", e.getMessage());
            response.setStatusLine(500);
            response.setHeadInfo("content-type", WebApp.contentTypeMappings.get("html"));
            String bodytext = response.generateError(response.getStatusLine().toString(),
                    WebApp.statusCodeMappings.get(response.getCode()), "报告", "服务器内部错误", "读取静态资源时服务器发生错误！");
            response.setBodyText(bodytext);
            response.pushToClient();
        }
        if (file != null && file.isFile()) {
            // 对文件名进行匹配，区分下载和返回
            String url = request.getUrl();
            String pattern = "";
            String typeContent = "";
            if (url.contains(".")) {
                pattern = url.substring(url.lastIndexOf(".") + 1, url.length());
                typeContent = WebApp.contentTypeMappings.get(pattern);
                if (typeContent != null) {
                    response.setHeadInfo("content-type", typeContent);
                }
            }
            if (pattern.equals("html") || pattern.equals("js") || pattern.equals("css") || pattern.equals("txt")) {
                // 返回文本类型静态资源
                try {
                    BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));
                    byte[] data = new byte[bi.available()];
                    int len = bi.read(data);
                    CloseUtil.colseIo(bi);
                    String contentText = new String(data, 0, len);
                    response.setStatusLine(200);
                    response.setHeadInfo("connection", "close");
                    response.setBodyText(contentText);
                    response.pushToClient();
                } catch (IOException e) {
                    logger.error("读取html/css/js静态资源的过程出错", e.getMessage());
                    response.setStatusLine(500);
                    response.setHeadInfo("content-type", WebApp.contentTypeMappings.get("html"));
                    String bodytext = response.generateError(response.getStatusLine().toString(),
                            WebApp.statusCodeMappings.get(response.getCode()), "报告", "服务器内部错误", "读取静态资源时服务器发生错误！");
                    response.setBodyText(bodytext);
                    response.pushToClient();
                }
            } else if (pattern.equals("gif") || pattern.equals("jpg") || pattern.equals("png")
                    || pattern.equals("ico")) {
                // 返回图片类型静态资源
                BufferedInputStream fis;
                try {
                    // img中的src不需要base64编码，不需要响应头
                    fis = new BufferedInputStream(new FileInputStream(file));
                    byte[] buffer = new byte[fis.available()];
                    int len = fis.read(buffer);
                    fis.close();
                    BufferedOutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                    toClient.write(buffer);
                    toClient.flush();
                } catch (IOException e) {
                    logger.error("读取img静态资源的过程出错", e.getMessage());
                    response.setStatusLine(500);
                    response.setHeadInfo("content-type", WebApp.contentTypeMappings.get("html"));
                    String bodytext = response.generateError(response.getStatusLine().toString(),
                            WebApp.statusCodeMappings.get(response.getCode()), "报告", "服务器内部错误", "读取静态资源时服务器发生错误！");
                    response.setBodyText(bodytext);
                    response.pushToClient();
                }
            }
        } else {
            // 找不到对应的资源或该url没有映射
            response.setStatusLine(404);
            response.setHeadInfo("content-type", WebApp.contentTypeMappings.get("html"));
            String bodytext = response.generateError(response.getStatusLine().toString(),
                    WebApp.statusCodeMappings.get(response.getCode()), "报告", "请求的资源" + request.getRawUrl() + "不可用",
                    "找不到指定的静态资源文件或无法找到指定url的处理器！");
            response.setBodyText(bodytext);
            response.pushToClient();
        }
    }
}
